package features.advance.mybatis.parser;

import org.apache.ibatis.builder.BuilderException;
import org.apache.ibatis.builder.xml.XMLMapperEntityResolver;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.parsing.XNode;
import org.apache.ibatis.parsing.XPathParser;
import org.w3c.dom.Document;
import org.xml.sax.*;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.Reader;
import java.util.Properties;

/**
 * @author LIN
 * @date 2021-07-06
 */
public class XPathTest {

    private Document createDocument(InputSource inputSource) {
        boolean validation = true;
        EntityResolver entityResolver = new XMLMapperEntityResolver();
        // important: this must only be called AFTER common constructor
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setValidating(validation);

            factory.setNamespaceAware(false);
            factory.setIgnoringComments(true);
            factory.setIgnoringElementContentWhitespace(false);
            factory.setCoalescing(false);
            factory.setExpandEntityReferences(true);

            DocumentBuilder builder = factory.newDocumentBuilder();
            builder.setEntityResolver(entityResolver);
            builder.setErrorHandler(new ErrorHandler() {

                @Override
                public void warning(SAXParseException e) throws SAXException {

                }

                @Override
                public void error(SAXParseException e) throws SAXException {

                }

                @Override
                public void fatalError(SAXParseException e) throws SAXException {

                }
            });
            return builder.parse(inputSource);
        } catch (Exception e) {
            throw new BuilderException("Error creating document instance.  Cause: " + e, e);
        }
    }

    public static void main(String[] args) {
        String resource = "mapper/MapperConfig.xml";
        try (Reader resourceAsReader = Resources.getResourceAsReader(resource)) {
            Properties properties = new Properties();
            properties.setProperty("driver","com.mysql.cj.jdbc.Driver");
            properties.setProperty("url","jdbc:mysql://localhost:3306/erpcg_pd?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8");
            properties.setProperty("username","root");
            XPathParser xPathParser = new XPathParser(resourceAsReader, true, properties,new XMLMapperEntityResolver());
            XNode root = xPathParser.evalNode("configuration");
            root.evalNode("mappers").getChildren().forEach(e->{
                System.out.println(e.getStringAttribute("resource"));
            });
        }catch (Exception e){
            e.printStackTrace();
        }finally {

        }
    }

}
